package com.javatest.db;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/7/26 16:15
 * JDBC操作工具类
 */
public class JdbcUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(JdbcUtils.class);
    private static DataSource dataSourceSSO = null;

    static {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("dataSourceCfg.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
            // 数据源只能创建一次
            dataSourceSSO = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            LOGGER.error("[jdbcutils]", e);
        }
    }

    /**
     * 返回数据源的一个Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return dataSourceSSO.getConnection();
    }

    /**
     * 释放connection链接
     *
     * @param connection
     */
    public static void releaseConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOGGER.error("[jdbcutils]", e);
            }
        }
    }
}
